//
//  HomeMoreController.m
//  SleepingElf
//
//  Created by karong on 2023/10/19.
//

#import "HomeMoreController.h"
#import "HomeMoreItemController.h"
#import "HomeClassifyItemCell.h"
#import "HomeModel.h"
#import "ClassListRequest.h"

@interface HomeMoreController () <HomeMoreItemControllerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSMutableDictionary *contentVCDict;
@property (nonatomic, assign) CGFloat contentHeight;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) HomeClassify * classify;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *selectImageArray;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *selectLabelArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selectItemWidth;
@property (weak, nonatomic) IBOutlet UIView *selectView;
@property (nonatomic, strong) NSMutableDictionary * selectDic;
@end

@implementation HomeMoreController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadClassListRequest];
    [self layoutSelectView];
}

- (void)loadClassListRequest {
    [ClassListRequest loadSleepPlayClasslistWithClassify_id:self.category_id success:^(id obj) {
        self.classify = obj;
        self.title = self.classify.name;
        HomeClassify * classity = [HomeClassify new];
        classity.id = 0;
        classity.name = WSLocalized(@"全部");
        NSMutableArray * array = [[NSMutableArray alloc]initWithArray:self.classify.children];
        [array insertObject:classity atIndex:0];
        self.classify.children = array;
        self.selectIndex = 0;
        [self viewLayout];
        [self setContentVCWithIndex:self.selectIndex];
        [self.listView reloadData];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
    }];
}

- (void)viewLayout {
    [self.scrollView setContentSize:CGSizeMake(kScreenWidth * self.classify.children.count, self.contentHeight)];
}

- (void)layoutSelectView {
    NSArray * allValues = self.selectDic.allValues;
    for (int i = 0; i < 3; i++) {
        UIImageView * img = self.selectImageArray[i];
        UILabel * label = self.selectLabelArray[i];
        if (i < allValues.count) {
            MusicModel * music = allValues[i];
            [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:music.cover] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                    if (image) {
                        image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
                        img.image = image;
                        img.tintColor = [UIColor colorFromHexRGB:@"ffffff"];
                    }
                }];
            label.text = SEEmptyStr(music.title);
        }
        else {
            img.image = nil;
            label.text = @"";
        }
    }
}

- (UIViewController *)addHomeMoreItemController:(NSInteger)classify_id {
    HomeMoreItemController * target = (HomeMoreItemController *)[self.storyboard instantiateViewControllerWithIdentifier:@"HomeMoreItemController"];
    target.delegate = self;
    target.classify_id = classify_id;
    target.view.frame = CGRectMake(0, 0, SEScreenWidth, self.contentHeight);
    return target;
}

// 获取並且添加子控制器
- (void)setContentVCWithIndex:(NSInteger)index {
    BOOL animated = YES;
    if(self.contentVCDict.count == 0) {
        animated = NO;
    }
    UIViewController *vc = self.contentVCDict[@(index)];
    if(!vc) {
        HomeClassify * classity = self.classify.children[index];
        vc = [self addHomeMoreItemController:classity.id];
        vc.view.frame = self.scrollView.bounds;
        vc.view.mj_x = SEScreenWidth * index;
        vc.view.mj_y = 0;
        [self.scrollView addSubview:vc.view];
        [self addChildViewController:vc];
        self.contentVCDict[@(index)] = vc;
    }
    [(HomeMoreItemController *)vc reloadData];
    [self.scrollView setContentOffset:CGPointMake(kScreenWidth * index, 0) animated:animated];
}

- (IBAction)randomAction:(id)sender {
    HomeMoreItemController * target = self.contentVCDict[@(0)];
    HomeMoreItemController * currTarget = self.contentVCDict[@(self.selectIndex)];
    if (target) {
        NSArray * array = [target randomMusic];
        for (int i = 0; i < array.count; i++) {
            [self homeMoreItemControllerDidSelectMusic:array[i]];
        }
        [currTarget reloadData];
    }
}

- (IBAction)musicAction:(id)sender {
    if (self.navigationController) {
        [self.tabBarController setSelectedIndex:2];
        [self.navigationController popToRootViewControllerAnimated:NO];
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        CGFloat x = scrollView.contentOffset.x / SEScreenWidth;
        [self setContentVCWithIndex:x];
        self.selectIndex = x;
        [self.listView reloadData];
    }
}

#pragma mark - UICollectionViewDelete

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.classify.children.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeClassifyItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeClassifyItemCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.classify.children[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 13, 0, 13);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeClassify * homeClassify = self.classify.children[indexPath.row];
    CGFloat width = [homeClassify.name boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14 weight:(UIFontWeightMedium)]} context:nil].size.width;
    return CGSizeMake(width + 18, 22);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectIndex = indexPath.row;
    [self setContentVCWithIndex:self.selectIndex];
    [self.listView reloadData];
}

- (NSMutableDictionary *)contentVCDict {
    if (!_contentVCDict) {
        _contentVCDict = [[NSMutableDictionary alloc]init];
    }
    return _contentVCDict;
}

- (CGFloat)contentHeight {
    if (_contentHeight <= 0) {
        _contentHeight = SEScreenWidth - self.view.safeAreaInsets.top - 30 - 30 - 30 - 44;
    }
    return _contentHeight;
}

#pragma mark - HomeMoreItemControllerDelegate
- (BOOL)homeMoreItemControllerMusicIsSelect:(MusicModel *)music {
    BOOL rec = NO;
    if (music) {
        rec = [self.selectDic.allKeys containsObject:@(music.id)];
    }
    return rec;
}

- (void)homeMoreItemControllerDidSelectMusic:(MusicModel *)music {
    if (music) {
        if ([self.selectDic.allKeys containsObject:@(music.id)]) {
            [self.selectDic removeObjectForKey:@(music.id)];
        }
        else {
            if (self.selectDic.allKeys.count < 3) {
                [self.selectDic setObject:music forKey:@(music.id)];
            }
        }
    }
    [[PlayerManager shared]playWithMusics:self.selectDic.allValues];
    [self layoutSelectView];
}

- (NSMutableDictionary *)selectDic {
    if (!_selectDic) {
        _selectDic = [NSMutableDictionary new];
        if (!self.navigationController) {
            for (MusicModel * music in appConfig.lastMusicArray) {
                [_selectDic setObject:music forKey:@(music.id)];
            }
        }
        
    }
    return _selectDic;
}
@end
